package com.Ashtar.controller;

import com.Ashtar.domain.Book;
import com.Ashtar.service.BookService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.Ashtar.controller.Code.*;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        return new Result(flag ? SAVE_OK: SAVE_ERR, flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        return new Result(flag ? DELETE_OK: DELETE_ERR, flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag ? UPDATE_OK: UPDATE_ERR, flag);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Book book = bookService.getById(id);
        boolean flag = book != null ? true : false;
        Integer code = flag ? GET_OK : GET_ERR;
        String msg = flag ? "" : "数据查询失败，重新尝试";
        return new Result(code, book, msg);
    }

    @GetMapping
    public Result getAll() {
        List<Book> books = bookService.list();
        boolean flag = books != null ? true : false;
        Integer code = flag ? GET_OK : GET_ERR;
        String msg = flag ? "" : "数据查询失败，重新尝试";
        return new Result(code, books, msg);
    }

    @PostMapping("/{currentPage}/{pageSize}")
    public Result getPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize){
        IPage page = bookService.getPage(currentPage, pageSize);
        boolean flag = page != null ? true : false;
        Integer code = flag ? GET_OK : GET_ERR;
        String msg = flag ? "" : "数据查询失败，重新尝试";
        return new Result(flag == true ? DELETE_OK : DELETE_ERR, msg);
    }
}
